package com.jt.sso.server.service.impl;

import com.jt.sso.server.mapper.UserMapper;
import com.jt.sso.server.model.Permission;
import com.jt.sso.server.model.Role;
import com.jt.sso.server.model.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;


@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userMapper.findOneByUsername(username);
        if (user==null)
            return null;
        //根据用户的id查询用户的所有权限
        List<Permission> ps= userMapper
                .findUserPermissionsById(user.getId());
        //根据登录需求,需要将ps对象转换为String[]类型
        String[] auth=new String[ps.size()];
        int i=0;
        for(Permission p : ps){
            auth[i]=p.getPermissionName();
            i++;
        }
        //新增的代码↓↓↓↓↓↓↓↓
        //查询当前用户的所有角色
        List<Role> roles=userMapper.findUserRolesById(
                user.getId());
        auth= Arrays.copyOf(auth,
                auth.length+roles.size());
        for(Role role:roles){
            auth[i++]=role.getRolename();
        }
        //新增代码结束↑↑↑↑↑↑

        //构建UserDetails对象
        UserDetails u= org.springframework.security.core.userdetails
                .User.builder()
                .username(user.getUserName())
                .password(user.getPassword())
                .authorities(auth)//赋予当前登录用户权限
                .build();
        //最后千万别忘了返回u
        return  u;
    }
}
